import re
import sys
import os
import argparse
#技能效果类
class Effect:
    name: str
    contents = []
    type: str
    def __init__(self, name, contents, type):
        self.name = name
        self.contents = contents
        self.type = type
        


#水天一色自制技能重构器
class SkillRecoder:

    def __init__(self, skillname:str,strname:str,content:str):
        
         #接受的原始文本
        self.code = content
       
        if not self.code:
            raise ValueError("必须提供输入代码或有效的输入文件")
        
        self.localname =skillname
        self.strname = strname
        self.skillcode=[]
        self._extract_skill_effects()
        self.init_selfcode()
        
        for effectname in self.effects:
            effect = self.effects[effectname]
        
            self.skillcode.append(self.transform(effect))

        self.end_selfcode()

        #




    #分类技能类别，然后分别处理
    def _extract_skill_type(self,content):
        """从技能代码中提取技能类型"""
        match = re.search(r'fk\.Create(\w+Skill)', content )
        if match:
            # 提取类型名称并移除"Skill"后缀
            skill_type = match.group(1)
            if skill_type.endswith("Skill"):
                skill_type = skill_type[:-5]  # 移除"Skill"后缀
            return skill_type
        return None
    
    
    def init_selfcode(self):
        tags = self.extract_skill_tags(self.code)
        tagstr=""
        self.skillcode.append(f'local {self.localname} = fk.CreateSkill {{')
        self.skillcode.append(f'  name = "{self.strname}",')
        for tag in tags:
            tagstr += f'{tag},'
        self.skillcode.append(f'  tags = {{ {tagstr} }},')
        self.skillcode.append('}')
        self.skillcode.append('')

    def end_selfcode(self):
        self.skillcode.append(f'return {self.localname}')

    def _extract_skill_effects(self):
        """分割技能效果"""
        self.effects = {}
        skill_pattern = re.compile(r'local\s+(\w+)\s*=\s*fk\.Create\w+Skill\s*\{', re.IGNORECASE)
        for match in skill_pattern.finditer(self.code):
            skill_name = match.group(1) 
            start_pos = match.start()
            level = 1
            end_pos = match.end()
            while end_pos < len(self.code) and level > 0:
                char = self.code[end_pos]
                if char == '{':
                    level += 1
                elif char == '}':
                    level -= 1
                end_pos += 1
            content = self.code[start_pos:end_pos]  # 提取完整技能内容
            self.effects[skill_name]= Effect(skill_name, content, self._extract_skill_type(content)) 



    #触发技文本处理
    def _process_trigger_body(self, body):
        """处理触发技函数体中的self.name和hasSkill(self)"""
        # 替换player:hasSkill(self)为player:hasSkill(localname.name)
        body = re.sub(r'(\w+):hasSkill\s*\(\s*self(?:\.name)?\s*\)', rf'\1:hasSkill({self.localname}.name)', body)
        body = body.replace('Self', 'player')
        
        
        # 替换player:usedSkillTimes(self.name, xxx)为player:usedSkillTimes(localname.name, xxx)
        body = re.sub(r'(\w+):usedSkillTimes\s*\(\s*self\.name', rf'\1:usedSkillTimes({self.localname}.name', body)
        
        # 替换一般的self.name为localname.name
        body = body.replace('self.name', f'{self.localname}.name')
        body = re.sub(r'main_skill\s*=\s*', '--', body)
        
        # 替换self.cost_data相关操作
        #body = re.sub(r'self\.cost_data\s*=\s*([^=,\n;]+)', r'event:setCostData(self, \1)', body)
        
        body = re.sub(
            r'self\.cost_data\s*=(?!=)\s*((?:{(?:[^{}]*|{[^{}]*})*})|[^,;\n]*)',
           
            r'event:setCostData(self, \1)',
            body
        )
        
   
        body = re.sub(r'local\s+(\w+)\s*=\s*self\.cost_data', r'local \1 = event:getCostData(self)', body)
        body = re.sub(r'(\w+)\s*=\s*self\.cost_data(?!\w)', r'\1 = event:getCostData(self)', body)
        body = re.sub(r'self\.cost_data\s*==\s*', r'event:getCostData(self) == ', body)
        
        return body

    def transform_viewas_skill(self):
        """转换视为技为新格式"""
        result = []
        
        # 提取基本信息
        name_match = re.search(r'name\s*=\s*"([^"]+)"', self.code)
        name = name_match.group(1) if name_match else self.localname
        
        # 提取其他属性
        attrs = {}
        for attr in ['anim_type', 'card_num', 'pattern', 'prompt']:
            match = re.search(rf'{attr}\s*=\s*([^,\}}]+)', self.code)
            if match:
                attrs[attr] = match.group(1).strip()
        
        # 提取函数
        functions = {}
        # 定义可能的视为技函数列表
        func_list = ['card_filter', 'view_as', 'enabled_at_play', 'enabled_at_response', 'before_use', 'after_use', 'dynamic_desc']
        for func in func_list:
            pattern = rf'{func}\s*=\s*function\s*\(([^)]*)\)(.*?)end,'
            match = re.search(pattern, self.code, re.DOTALL)
            if match:
                params = match.group(1).strip()
                body = match.group(2).strip()
                
                # 修正参数顺序
                if func in ['card_filter', 'view_as']:
                    params = re.sub(r'self,\s*to_select,\s*selected', 'self, player, to_select, selected', params)
                    params = re.sub(r'self,\s*cards', 'self, player, cards', params)
                
                # 替换Self为player
                body = body.replace('Self', 'player')
                # 替换self.name为localname.name
                body = body.replace('self.name', f'{self.localname}.name')
                
                functions[func] = (params, body)
        
        # 创建基本结构
        result.append(f'local {self.localname} = fk.CreateSkill {{')
        result.append(f'  name = "{name}"')
        result.append('}')
        result.append('')
        
        # 创建addEffect
        result.append(f'{self.localname}:addEffect("viewas", {{{{')
        
        # 添加属性
        for attr, value in attrs.items():
            result.append(f'  {attr} = {value},')
        
        # 添加函数
        for func, (params, body) in functions.items():
            result.append(f'  {func} = function({params})')
            result.append(f'    {body}')
            result.append('  end,')
        
        result.append('}})')
        result.append('')
        
        return '\n'.join(result)

    def transform_active_skill(self):
        """转换主动技为新格式"""
        result = []
        
        # 提取基本信息
        name_match = re.search(r'name\s*=\s*"([^"]+)"', self.code)
        name = name_match.group(1) if name_match else self.localname
        
        # 提取其他属性
        attrs = {}
        for attr in ['anim_type', 'card_num', 'target_num', 'prompt', 'min_target_num', 'max_target_num']:
            match = re.search(rf'{attr}\s*=\s*([^,\}}]+)', self.code)
            if match:
                attrs[attr] = match.group(1).strip()
        
        # 提取函数
        functions = {}
        # 定义可能的主动技函数列表
        func_list = ['can_use', 'card_filter', 'target_filter', 'feasible', 'on_use', 'target_num']
        for func in func_list:
            pattern = rf'{func}\s*=\s*function\s*\(([^)]*)\)(.*?)end,'
            match = re.search(pattern, self.code, re.DOTALL)
            if match:
                params = match.group(1).strip()
                body = match.group(2).strip()
                
                # 修正参数顺序
                if func == 'card_filter':
                    params = re.sub(r'self,\s*to_select,\s*selected', 'self, player, to_select, selected', params)
                    body = body.replace('Self', 'player')
                elif func == 'target_filter':
                    params = re.sub(r'self,\s*to_select,\s*selected', 'self, player, to_select, selected', params)
                    body = body.replace('Self', 'player')
                
                # 替换self.name为localname.name
                body = body.replace('self.name', f'{self.localname}.name')
                
                functions[func] = (params, body)
        
        # 创建基本结构
        result.append(f'local {self.localname} = fk.CreateSkill {{')
        result.append(f'  name = "{name}"')
        result.append('}')
        result.append('')
        
        # 创建addEffect
        result.append(f'{self.localname}:addEffect("active", {{{{')
        
        # 添加属性
        for attr, value in attrs.items():
            result.append(f'  {attr} = {value},')
        
        # 添加函数
        for func, (params, body) in functions.items():
            result.append(f'  {func} = function({params})')
            result.append(f'    {body}')
            result.append('  end,')
        
        result.append('}})')
        result.append('')
        
        return '\n'.join(result)

    def transform_other_skills(self):
        """转换其他类型的技能为新格式"""
        type_map = {
            'DistanceSkill': 'distance',
            'ProhibitSkill': 'prohibit',
            'AttackRangeSkill': 'atkrange',
            'MaxCardsSkill': 'maxcards',
            'TargetModSkill': 'targetmod',
            'FilterSkill': 'filter',
            'InvaliditySkill': 'invalidity',
            'VisibilitySkill': 'visibility'
        }
        
        effect_type = type_map.get(self.skill_type[6:], self.skill_type[6:].lower())
        
        result = []
        
        # 提取基本信息
        name_match = re.search(r'name\s*=\s*"([^"]+)"', self.code)
        name = name_match.group(1) if name_match else self.localname
        
        # 提取其他属性和函数
        attrs = {}
        for line in self.code.split('\n'):
            line = line.strip()
            if '=' in line and 'function' not in line and line.endswith(','):
                parts = line.split('=', 1)
                attr = parts[0].strip()
                if attr != 'name':
                    value = parts[1].strip().rstrip(',')
                    attrs[attr] = value
        
        functions = {}
        for line in self.code.split('\n'):
            if 'function' in line and '=' in line:
                func_name = line.split('=')[0].strip()
                func_body = []
                capture = False
                for l in self.code.split('\n'):
                    if f'{func_name} = function' in l:
                        capture = True
                        params = l.split('function')[1].strip().rstrip(',')
                        func_body.append(f'function{params}')
                    elif capture and 'end,' in l:
                        func_body.append(l.replace('end,', 'end'))
                        capture = False
                        break
                    elif capture:
                        func_body.append(l)
                
                if func_body:
                    functions[func_name] = '\n'.join(func_body)
        
        # 创建基本结构
        result.append(f'local {self.localname} = fk.CreateSkill {{')
        result.append(f'  name = "{name}"')
        result.append('}')
        result.append('')
        
        # 创建addEffect
        result.append(f'{self.localname}:addEffect("{effect_type}", {{{{')
        
        # 添加属性
        for attr, value in attrs.items():
            result.append(f'  {attr} = {value},')
        
        # 添加函数
        for func, body in functions.items():
            result.append(f'  {func} = {body},')
        
        result.append('}})')
        result.append('')
        
        return '\n'.join(result)

    def extract_skill_content(self, code):
        """提取fk.CreatexxxSkill后大括号内的内容，包括括号"""
        # 匹配所有fk.CreatexxxSkill{开始的模式
        pattern = re.compile(r'fk\.Create\w+Skill\s*\{', re.IGNORECASE)
        match = pattern.search(code)
        
        if not match:
            return None
        
        start_pos = match.end() - 1  # 包含开始的'{'
        level = 1
        end_pos = start_pos + 1
        
        # 寻找匹配的结束括号
        while end_pos < len(code) and level > 0:
            char = code[end_pos]
            if char == '{':
                level += 1
            elif char == '}':
                level -= 1
            end_pos += 1
        
        if level == 0:
            # 提取内容（包括大括号）
            

            result=code[start_pos:end_pos]
            #再处理一下result
            result = self._process_trigger_body(result)

            result = self._process_viewas_body(result)
            return result
        else:
            # 如果没有找到匹配的结束括号
            return None
    

    def transform(self,effect):
        
        """将旧格式的技能代码转换为新格式"""
        
        if not effect.type:
            return "无法识别技能类型"
        
        result = []
        # 根据技能类型进行转换
        if effect.type == 'Trigger':
            events = self.extract_skill_events(effect.contents)
            refresh_events = self.extract_skill_refresh_events(effect.contents)

            if (not events) and (not refresh_events):
               
                return ""
          
           
            effect_content=self.extract_skill_content( effect.contents)#获取技能内容
            event_content=effect_content
            #如果有刷新函数，则提取刷新函数和非刷新
            refresh_content=""

            if refresh_events:
               event_content=self.extract_event_content(effect_content)
               refresh_content=self.extract_refresh_event_content(effect_content)
          
            #如果没有时间则默认无
            if  events:
                events_list = [e.strip() for e in events[0].split(',')]
                for event in events_list:
                    
                    result.append(self.writenewcode(self.localname, 
                    event, event_content))

            if refresh_events:
                refresh_events_list = [e.strip() for e in refresh_events[0].split(',')]
                for refresh_event in refresh_events_list:
     
                    result.append(self.writenewcode(self.localname, 
                    refresh_event, refresh_content))

        elif effect.type == 'ViewAs':
    
          result.append(self.writenewcode(self.localname, 
            "viewas", self.extract_skill_content(effect.contents),True))
        elif effect.type == 'Active':
        
            result.append(self.writenewcode(self.localname, 
            "active", self.extract_skill_content(effect.contents),True))
        else:
            result.append(self.writenewcode(self.localname, 
            effect.type.lower(), self.extract_skill_content(effect.contents),True))
        
        # 处理相关技能

        # 添加返回语句

        
        return '\n'.join(result)

    def writenewcode(self, localname, type, content,isstr:bool=False):
        """
        将技能内容转换为新格式
        :param localname: 技能的本地变量名
        :param type: 技能效果类型
        :param content: 技能内容（大括号内的部分，包括括号）
        :return: 新格式的技能代码，形式为localname:addEffect(type, content)
        """
        # 确保content是有效的
        if not content or not content.startswith('{') or not content.endswith('}'):
            return f"// 无法处理的内容: {content}"
        
        # 提取大括号内的实际内容（去掉大括号）
        inner_content = content[1:-1].strip()
        
        # 构建新格式的代码
        result = []

        

        if isstr:
            result.append(f'{localname}:addEffect("{type}", {{')
        else:
            result.append(f'{localname}:addEffect({type}, {{')
        
        # 添加内容，保持缩进
        lines = inner_content.split('\n')
        for line in lines:
            # 跳过空行
            if not line.strip():
                continue
            
            # 保持缩进，添加内容
            indent = '  '  # 基础缩进
            # 如果行本身已经有缩进，则保持原有缩进
            stripped_line = line.lstrip()
            if line != stripped_line:
                original_indent = line[:len(line) - len(stripped_line)]
                indent = original_indent
            
            result.append(f"{indent}{stripped_line}")
        
        result.append('})')
        
        return '\n'.join(result)

    def extract_skill_events(self, content):
        """提取技能事件"""
        events = list()
        pattern = re.compile(r'(?<!_)events\s*=\s*\{([^}]+)\}', re.IGNORECASE)
        if pattern.finditer(content):
            for match in pattern.finditer(content):
                events.append(match.group(1))

        return events
    
    def extract_skill_refresh_events(self, content):
        """提取技能刷新事件"""
        events = list()
        pattern = re.compile(r'refresh_events\s*=\s*\{([^}]+)\}', re.IGNORECASE)
        if pattern.finditer(content):
            for match in pattern.finditer(content):
                events.append(match.group(1))

        return events

    def extract_skill_tags(self, content):
        """
        从技能代码中提取技能标签，返回完整的标签格式（如Skill.Compulsory）
        :param content: 技能代码内容
        :return: 完整的技能标签字符串列表
        """
        tags = []
        
        # 匹配多个标签格式，如 frequency = {Skill.Limited, Skill.Compulsory}
        pattern = re.compile(r'frequency\s*=\s*([^,=]+),', re.IGNORECASE)

        for tag_match in pattern.finditer(content):

            tag = tag_match.group(1)
            if tag not in tags:
                tags.append(tag)
        
        return tags

    def _process_viewas_body(self, content):
        """处理视为技的body"""
        # 提取基本信息
        patterns = {
            'card_filter': re.compile(r'card_filter\s*=\s*function\s*\(self,\s*(\w+),\s*(\w+)\)'),
            'view_as': re.compile(r'view_as\s*=\s*function\s*\(self,\s*(\w+)\)'),
            'prompt': re.compile(r'prompt\s*=\s*function\s*\(self,\s*(\w+),\s*(\w+)\)'),
            'feasible': re.compile(r'feasible\s*=\s*function\s*\(self,\s*(\w+),\s*(\w+)\)'),
       
            'target_filter': re.compile(r'target_filter\s*=\s*function\s*\(self,\s*(\w+),\s*(\w+)(?:,\s*(\w+))?(?:,\s*(\w+))?\)'),
          
        }

        replacements = {
            'card_filter': r'card_filter = function(self, player, \1, \2)',
            'view_as': r'view_as = function(self, player,\1)',
            'prompt': r'prompt = function(self, player, \1, \2)',
            'feasible': r'feasible = function(self, player, \1, \2)',
    
            'target_filter': r'target_filter = function(self, player, \1, \2)',

        }



        for func in patterns:
            content = patterns[func].sub(replacements[func], content)
        
        return content

    def extract_event_content(self, content):
        """
        从技能内容中提取从开头到refresh_events关键字之前的所有内容
        :param content: 技能代码内容
        :return: 提取出的内容
        """
        # 查找refresh_events的位置
        refresh_pos = content.find('refresh_events')
        if refresh_pos == -1:
            return content  # 如果没有找到refresh_events，返回整个内容
        
        # 从内容开始到refresh_events前查找最后一个'end,'的位置
        # 首先获取到refresh_events前的内容
        before_refresh = content[:refresh_pos]
        
        # 查找最后一个'end,'的位置
        end_pos = before_refresh.rfind('end,')
        if end_pos == -1:
            return before_refresh  # 如果没有找到'end,'，返回到refresh_events前的全部内容
        
        # 返回从开始到'end,'后的所有内容（包括'end,'）
        return before_refresh[:end_pos+4]+'}'
    
    def extract_refresh_event_content(self, content):
        """
        从技能内容中提取refresh_events关键字及其之后的所有内容
        :param content: 技能代码内容
        :return: 提取出的内容
        """
        # 查找refresh_events的位置
        refresh_pos = content.find('refresh_events')
        if refresh_pos == -1:
            return content  # 如果没有找到refresh_events，返回整个内容
        
        # 提取refresh_events及其后面的所有内容
        refresh_content = content[refresh_pos:]
        
        # 返回完整的代码块，添加花括号
        return '{' + refresh_content
    
